﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;

namespace Common.Controls
{
    public partial class TextboxValidated : UserControl
    {
        public string ValidationExpression { get; set; }
        public string Watermark { get; set; }
        public string Text
        {
            get { return tbTextBox.Text; }
            set { tbTextBox.Text = value; }
        }
        public event TextChangedEventHandler TextChanged;
        private Regex _regex = null;
        private bool _validated = false;
        public bool Validated
        {
            get
            {
                return _validated;
            }
        }
        public TextboxValidated()
        {
            InitializeComponent();
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            tbTextBox.Watermark = Watermark;
            if (string.IsNullOrEmpty(ValidationExpression) == false)
            {
                _regex = new Regex(ValidationExpression);
            }
            else
            {
                _validated = true;
            }
            SetErrorVisibility();
        }
        private void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            CheckText();
        }
        private void tbTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckText();
            TextChanged(sender, e);
        }
        private void CheckText()
        {
            if (_regex != null)
            {
                if (_regex.IsMatch(tbTextBox.Text))
                {
                    _validated = true;
                }
                else
                {
                    _validated = false;
                }
            }
            SetErrorVisibility();
        }
        private void SetErrorVisibility()
        {
            if (_validated)
            {
                imgError.Visibility = Visibility.Collapsed;
                colImage.Width = new GridLength(0);
            }
            else
            {
                if (string.IsNullOrEmpty(tbTextBox.Text))
                {
                    imgError.Visibility = Visibility.Collapsed;
                    colImage.Width = new GridLength(0);
                }
                else
                {
                    imgError.Visibility = Visibility.Visible;
                    colImage.Width = new GridLength(16);
                }
            }
        }




    }
}
